package org.spring.aicloud.controller;


import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.baidubce.qianfan.model.image.Text2ImageResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.spring.aicloud.entity.Answer;
import org.spring.aicloud.entity.enums.AIModelEnum;
import org.spring.aicloud.entity.enums.AITypeEnum;
import org.spring.aicloud.service.IAnswerService;
import org.spring.aicloud.utils.MinIoUtil;
import org.spring.aicloud.utils.ResponseEntity;

import org.spring.aicloud.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.util.Base64;
import java.util.UUID;

/**
 * @author yexiebao
 * @date 2025/6/1
 * 百度千帆大模型
 */
@RestController
@RequestMapping("/qianfan")
public class QianfanController {
    @Value("${qianfan.access-key}")
    private String accessKey;
    @Value("${qianfan.secret-key}")
    private String secretKey;
    @Resource
    private MinIoUtil minIoUtil;
    @Resource
    private IAnswerService answerService;

    /**
     * 聊天
     * @param question
     * @return
     */
    @RequestMapping("/chat")
    public ResponseEntity  chat(String question) {
        if(!StringUtils.hasLength(question)){
            return ResponseEntity.error("请先输入内容");
        }
        ChatResponse response = new Qianfan(accessKey, secretKey).chatCompletion()
                .model("ERNIE-Speed-128K")
                .addMessage("user", question)
                .execute();
        String result = response.getResult();
        // 保存答案到数据库
        Answer answer = new Answer();
        answer.setTitle(question);
        answer.setContent(result);
        answer.setModel(AIModelEnum.WENXIN.getCode());
        answer.setType(AITypeEnum.CHAT.getCode());
        answer.setUid(SecurityUtil.getCurrentUser().getUid());
        boolean saveResult = answerService.save(answer);
        if(!saveResult){
            return ResponseEntity.error("结果保存失败");
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 图片生成
     * @param question
     * @return
     */
    @RequestMapping("/draw")
    public ResponseEntity draw(String question) {
        if(!StringUtils.hasLength(question)){
            return ResponseEntity.error("请先输入内容");
        }
        Text2ImageResponse response = new Qianfan(accessKey, secretKey).text2Image()
                .prompt(question)
                .execute();
        // 将 base64 编码的图片解码并上传到 MinIO，返回图片访问链接
        String imgUrl;
        try {
            // 获取 base64 编码字符串（去掉可能的前缀）
            String base64Str = response.getData().get(0).getB64Image();
            if (base64Str.startsWith("data:image")) {
                //base64Str.indexOf(",") 找到逗号 , 的位置（也就是元信息和真正内容的分界点）；
                //substring(... + 1) 表示从逗号之后开始截取，即只留下 base64 纯数据部分。
                base64Str = base64Str.substring(base64Str.indexOf(",") + 1);
            }

            // 解码成字节流
            byte[] imageBytes = Base64.getDecoder().decode(base64Str);
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes)) {
                // 构造唯一文件名（加 .png 后缀更规范）
                String fileName = "qianfan-draw-" + UUID.randomUUID().toString().replace("-", "") + ".png";
                // 上传并获取图片链接
                imgUrl = minIoUtil.upload(fileName, inputStream, "image/png");
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印错误堆栈，方便排查
            throw new RuntimeException("图片上传失败：" + e.getMessage(), e);
        }
        // 添加答案到数据库
        Answer answer = new Answer();
        answer.setTitle(question);
        answer.setContent(imgUrl);
        answer.setModel(AIModelEnum.WENXIN.getCode());
        answer.setType(AITypeEnum.DRAW.getCode());
        answer.setUid(SecurityUtil.getCurrentUser().getUid());
        boolean saveResult = answerService.save(answer);
        if(!saveResult){
            return ResponseEntity.error("结果保存失败");
        }

        return ResponseEntity.ok(imgUrl);
    }

    /**
     * 获取对话历史
     */
    @RequestMapping("/getchatlist")
    public ResponseEntity getChatList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",uid);
        queryWrapper.eq("type", AITypeEnum.CHAT.getCode());
        queryWrapper.eq("model", AIModelEnum.WENXIN.getCode());
        queryWrapper.orderByDesc("aid");
        return ResponseEntity.ok(answerService.list(queryWrapper));
    }
    /**
     * 获取绘画历史
     */
    @RequestMapping("/getdrawlist")
    public ResponseEntity getDrawList() {
        Long uid =SecurityUtil.getCurrentUser().getUid();
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",uid);
        queryWrapper.eq("type", AITypeEnum.DRAW.getCode());
        queryWrapper.eq("model",AIModelEnum.WENXIN.getCode());
        queryWrapper.orderByDesc("aid");
        return ResponseEntity.ok(answerService.list(queryWrapper));
    }
}
